"""
管理后台 - 套餐管理接口
"""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.dependencies import get_db, get_current_user
from app.schemas.common import ResponseModel, PaginatedResponse
from app.schemas.content import (
    ServicePackageCreate, ServicePackageUpdate, ServicePackageResponse,
    CustomPackageCreate, CustomPackageUpdate, CustomPackageResponse,
    PackageFeatureCreate, PackageFeatureUpdate, PackageFeatureResponse
)
from app.crud.base import CRUDBase
from app.models.content import ServicePackage, CustomPackage, PackageFeature


router = APIRouter()

# CRUD 实例
crud_service_package = CRUDBase[ServicePackage, ServicePackageCreate, ServicePackageUpdate](ServicePackage)
crud_custom_package = CRUDBase[CustomPackage, CustomPackageCreate, CustomPackageUpdate](CustomPackage)
crud_package_feature = CRUDBase[PackageFeature, PackageFeatureCreate, PackageFeatureUpdate](PackageFeature)


# ==================== 技术服务套餐 ====================

@router.get("/service", response_model=ResponseModel)
async def get_service_packages(
    page: int = Query(1, ge=1),
    page_size: int = Query(10, ge=1, le=100),
    status: Optional[int] = Query(None),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """获取技术服务套餐列表"""
    filters = {}
    if status is not None:
        filters["status"] = status
    
    skip = (page - 1) * page_size
    packages = await crud_service_package.get_multi(db, skip=skip, limit=page_size, filters=filters)
    total = await crud_service_package.get_count(db, filters=filters)
    
    return ResponseModel(
        data=PaginatedResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=[ServicePackageResponse.model_validate(p) for p in packages]
        )
    )


@router.get("/service/{package_id}", response_model=ResponseModel)
async def get_service_package(
    package_id: int,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """获取技术服务套餐详情"""
    package = await crud_service_package.get_by_id(db, id=package_id)
    if not package:
        raise HTTPException(status_code=404, detail="套餐不存在")
    
    return ResponseModel(data=ServicePackageResponse.model_validate(package))


@router.post("/service", response_model=ResponseModel)
async def create_service_package(
    package_in: ServicePackageCreate,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """创建技术服务套餐"""
    package = await crud_service_package.create(db, obj_in=package_in)
    return ResponseModel(
        code=201,
        message="创建成功",
        data=ServicePackageResponse.model_validate(package)
    )


@router.put("/service/{package_id}", response_model=ResponseModel)
async def update_service_package(
    package_id: int,
    package_in: ServicePackageUpdate,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """更新技术服务套餐"""
    package = await crud_service_package.get_by_id(db, id=package_id)
    if not package:
        raise HTTPException(status_code=404, detail="套餐不存在")
    
    package = await crud_service_package.update(db, db_obj=package, obj_in=package_in)
    return ResponseModel(
        message="更新成功",
        data=ServicePackageResponse.model_validate(package)
    )


@router.delete("/service/{package_id}", response_model=ResponseModel)
async def delete_service_package(
    package_id: int,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """删除技术服务套餐"""
    success = await crud_service_package.delete(db, id=package_id)
    if not success:
        raise HTTPException(status_code=404, detail="套餐不存在")
    
    return ResponseModel(message="删除成功")


# ==================== 定制开发套餐 ====================

@router.get("/custom", response_model=ResponseModel)
async def get_custom_packages(
    page: int = Query(1, ge=1),
    page_size: int = Query(10, ge=1, le=100),
    category: Optional[str] = Query(None),
    status: Optional[int] = Query(None),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """获取定制开发套餐列表"""
    filters = {}
    if category:
        filters["category"] = category
    if status is not None:
        filters["status"] = status
    
    skip = (page - 1) * page_size
    packages = await crud_custom_package.get_multi(db, skip=skip, limit=page_size, filters=filters)
    total = await crud_custom_package.get_count(db, filters=filters)
    
    return ResponseModel(
        data=PaginatedResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=[CustomPackageResponse.model_validate(p) for p in packages]
        )
    )


@router.get("/custom/{package_id}", response_model=ResponseModel)
async def get_custom_package(
    package_id: int,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """获取定制开发套餐详情"""
    package = await crud_custom_package.get_by_id(db, id=package_id)
    if not package:
        raise HTTPException(status_code=404, detail="套餐不存在")
    
    return ResponseModel(data=CustomPackageResponse.model_validate(package))


@router.post("/custom", response_model=ResponseModel)
async def create_custom_package(
    package_in: CustomPackageCreate,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """创建定制开发套餐"""
    package = await crud_custom_package.create(db, obj_in=package_in)
    return ResponseModel(
        code=201,
        message="创建成功",
        data=CustomPackageResponse.model_validate(package)
    )


@router.put("/custom/{package_id}", response_model=ResponseModel)
async def update_custom_package(
    package_id: int,
    package_in: CustomPackageUpdate,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """更新定制开发套餐"""
    package = await crud_custom_package.get_by_id(db, id=package_id)
    if not package:
        raise HTTPException(status_code=404, detail="套餐不存在")
    
    package = await crud_custom_package.update(db, db_obj=package, obj_in=package_in)
    return ResponseModel(
        message="更新成功",
        data=CustomPackageResponse.model_validate(package)
    )


@router.delete("/custom/{package_id}", response_model=ResponseModel)
async def delete_custom_package(
    package_id: int,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """删除定制开发套餐"""
    success = await crud_custom_package.delete(db, id=package_id)
    if not success:
        raise HTTPException(status_code=404, detail="套餐不存在")
    
    return ResponseModel(message="删除成功")


# ==================== 套餐功能对照 ====================

@router.get("/features", response_model=ResponseModel)
async def get_package_features(
    page: int = Query(1, ge=1),
    page_size: int = Query(10, ge=1, le=100),
    feature_category: Optional[str] = Query(None),
    status: Optional[int] = Query(None),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """获取套餐功能对照列表"""
    filters = {}
    if feature_category:
        filters["feature_category"] = feature_category
    if status is not None:
        filters["status"] = status
    
    skip = (page - 1) * page_size
    features = await crud_package_feature.get_multi(db, skip=skip, limit=page_size, filters=filters)
    total = await crud_package_feature.get_count(db, filters=filters)
    
    return ResponseModel(
        data=PaginatedResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=[PackageFeatureResponse.model_validate(f) for f in features]
        )
    )


@router.get("/features/{feature_id}", response_model=ResponseModel)
async def get_package_feature(
    feature_id: int,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """获取套餐功能对照详情"""
    feature = await crud_package_feature.get_by_id(db, id=feature_id)
    if not feature:
        raise HTTPException(status_code=404, detail="功能对照不存在")
    
    return ResponseModel(data=PackageFeatureResponse.model_validate(feature))


@router.post("/features", response_model=ResponseModel)
async def create_package_feature(
    feature_in: PackageFeatureCreate,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """创建套餐功能对照"""
    feature = await crud_package_feature.create(db, obj_in=feature_in)
    return ResponseModel(
        code=201,
        message="创建成功",
        data=PackageFeatureResponse.model_validate(feature)
    )


@router.put("/features/{feature_id}", response_model=ResponseModel)
async def update_package_feature(
    feature_id: int,
    feature_in: PackageFeatureUpdate,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """更新套餐功能对照"""
    feature = await crud_package_feature.get_by_id(db, id=feature_id)
    if not feature:
        raise HTTPException(status_code=404, detail="功能对照不存在")
    
    feature = await crud_package_feature.update(db, db_obj=feature, obj_in=feature_in)
    return ResponseModel(
        message="更新成功",
        data=PackageFeatureResponse.model_validate(feature)
    )


@router.delete("/features/{feature_id}", response_model=ResponseModel)
async def delete_package_feature(
    feature_id: int,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """删除套餐功能对照"""
    success = await crud_package_feature.delete(db, id=feature_id)
    if not success:
        raise HTTPException(status_code=404, detail="功能对照不存在")
    
    return ResponseModel(message="删除成功")

